package com.bobi.tfca.ui.mainnavigation.user.member

import android.annotation.SuppressLint
import android.app.AlertDialog
import android.os.Bundle
import android.widget.Toast
import androidx.navigation.findNavController
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.bobi.tfca.R
import com.bobi.tfca.base.BaseFragment
import com.bobi.tfca.constants.PageElementIdConstant
import com.bobi.tfca.databinding.FragmentMemberStillBinding
import com.bobi.tfca.network.client.AppCache
import com.bobi.tfca.network.response.MemberResponse
import com.bobi.tfca.ui.adapter.MemberStillAdapter
import com.bobi.tfca.util.LogUtil


class MemberStillFragment : BaseFragment<FragmentMemberStillBinding, MemberManageFragmentVM>(
    FragmentMemberStillBinding::inflate,
    MemberManageFragmentVM::class.java,
    true
) {
    private lateinit var memberRV: RecyclerView

    @SuppressLint("ResourceType", "UseRequireInsteadOfGet")
    override fun initFragment(
        binding: FragmentMemberStillBinding,
        viewModel: MemberManageFragmentVM?,
        savedInstanceState: Bundle?
    ) {
        // 初始化RV
        initRecyclerView(binding, viewModel!!)

        // 监听viewmodel
        viewModel.apply {
            members.observe(this@MemberStillFragment) {
                val adapter = memberRV.adapter as MemberStillAdapter
                adapter.setItemList(it)
                adapter.notifyDataSetChanged()
            }
        }

        // 搜索查询
        binding.ivSearchIcon.setOnClickListener {
            val searchContent = binding.etSearchContent.text.toString()
            if (searchContent.isNullOrBlank()) {
                Toast.makeText(requireActivity(), "输入内容为空，请检查", Toast.LENGTH_SHORT).show()
            } else {
                viewModel.searchStillMemberByName(publicViewModel!!, searchContent, this)
            }
        }

        publicViewModel!!.apply {
            visiblePageElements.observe(viewLifecycleOwner) {
                val adapter = memberRV.adapter as MemberStillAdapter
                adapter.setHasRemoveAuthority(getElementVisibility(PageElementIdConstant.ITEM_MEMBER_STILL_TV_REMOVE))
                adapter.setHasPromotionAuthority(getElementVisibility(PageElementIdConstant.ITEM_MEMBER_STILL_TV_CHANGE_ROLE))
                adapter.notifyDataSetChanged()
            }
        }

    }

    /**
     * 初始化RV
     */
    private fun initRecyclerView(
        binding: FragmentMemberStillBinding,
        viewModel: MemberManageFragmentVM
    ) {
        // 获取RecyclerView实例
        memberRV = binding.rvMemberLeave

        // 获得所有活动
        val memberList: ArrayList<MemberResponse> = arrayListOf()
        // 设置布局管理器
        val linearLayoutManager = LinearLayoutManager(binding.root.context)
        linearLayoutManager.orientation = LinearLayoutManager.VERTICAL
        memberRV.layoutManager = linearLayoutManager
        memberRV.addItemDecoration(
            DividerItemDecoration(
                binding.root.context,
                LinearLayoutManager.VERTICAL
            )
        )
        val memberAdapter = MemberStillAdapter(this, memberList)

        // 设置监听器
        memberAdapter.setOnHeadsClickListener(object : MemberStillAdapter.OnItemClickListener {
            override fun onItemClick(position: Int) {
                // 设置跳转详情
                publicViewModel!!.member.value = memberAdapter.memberList[position]
                requireActivity().findNavController(R.id.app_nav)
                    .navigate(R.id.action_memberManageFragment_to_memberProfileFragment)
            }
        })
        memberAdapter.setOnRemoveClickListener(object : MemberStillAdapter.OnItemClickListener {
            override fun onItemClick(position: Int) {
                // 创建确认框
                val builder = AlertDialog.Builder(requireContext())
                builder.setTitle("移除")
                builder.setMessage("你确认移除会员吗")

                // 设置确认按钮和点击事件
                builder.setPositiveButton("确认") { dialog, which ->
                    // 获得所有选择会员id
                    val adapter = memberRV.adapter as MemberStillAdapter
                    val clickedMemberId = adapter.memberList[position].memberId
                    val memberId = AppCache.getMyInfo().memberId
                    LogUtil.i("clickedMemberId: $clickedMemberId,  memberId:$memberId")
                    if (memberId == clickedMemberId) {
                        Toast.makeText(requireActivity(), "不能移除自己", Toast.LENGTH_SHORT).show()
                    } else {
                        viewModel.removeAssMember(publicViewModel!!, this@MemberStillFragment, clickedMemberId)
                    }
                }

                // 设置取消按钮和点击事件
                builder.setNegativeButton("取消") { dialog, which ->
                }

                // 创建并显示确认框
                val dialog: AlertDialog = builder.create()
                dialog.show()
            }
        })
        // 提升按钮
        memberAdapter.setOnPromotionClickListener(object : MemberStillAdapter.OnItemClickListener {
            override fun onItemClick(position: Int) {
                val adapter = memberRV.adapter as MemberStillAdapter
                val clickedMemberId = adapter.memberList[position].memberId
                // 查询所有职位
                viewModel.getAllRoles(publicViewModel!!, this@MemberStillFragment, clickedMemberId)
            }
        })

        // 绑定Adapter
        memberRV.adapter = memberAdapter
    }

    override fun resumeFragment(viewModel: MemberManageFragmentVM?) {
        super.resumeFragment(viewModel)
        viewModel!!.findAllStillMembers(publicViewModel!!, this)
    }
}